﻿using System;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Square.Activity;
using Microsoft.SharePoint.Utilities;

namespace Square.Contents.Layouts.Square.Contents
{
    public partial class ItemSetting : LayoutsPageBase
    {
        #region Variable

        //설정할 웹 주소
        private string strWebUrl = string.Empty;
        //설정할 리스트 아이디
        private string strListId = string.Empty;
        //설정할 아이템 아이디
        private string strItemId = string.Empty;
        //설정할 아이템 폴더 주소
        private string strItemUrl = string.Empty;
        //설정할 아이템 부모 폴더 주소
        private string strPItemUrl = string.Empty;
        //설정할 아이템 부모 폴더 Depth
        private string strCrrDepth = string.Empty;

        #endregion

        #region Properties

        #region private string strConvertToString(object _value)
        /// <summary>
        /// object를 string로 변환해 준다.
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        private string strConvertToString(object _value)
        {
            string strValue = string.Empty;

            try
            {
                if (_value != null)
                {
                    strValue = _value.ToString();
                }
            }
            catch (Exception)
            {
            }

            return strValue;
        }
        #endregion

        #region public static string GetTextResource(string strResource, string strName)
        /// <summary>
        /// Global Resource 에서 매개변수로 넘겨진 키값으로 리소스 값을 가져온다. 오버로드 메서드 #2
        /// </summary>
        /// <param name="resxFile">리소스 파일명</param>
        /// <param name="strKey">리소스 키</param>
        /// <param name="uiLanguage">언어 정수값 예:1033 - 영어</param>
        /// <returns>키 값에 해당하는 리소스 값</returns>        
        public static string GetTextResource(string resxFile, string strKey)
        {
            string str = SPUtility.GetLocalizedString(string.Format("$Resources:{0},{1}", resxFile, strKey), resxFile, 1033);
            return str != null ? str : "";
        }
        #endregion

        #region public string GetCurrentUserLoginName()
        /// <summary>        
        /// 현재 사용자 로그인 아이디 가져오기
        /// </summary>
        /// <returns></returns>
        public string GetCurrentUserLoginName()
        {            
            string LoginName = string.Empty;

            //string authenType = HttpContext.Current.User.Identity.AuthenticationType;
            //if (authenType.Equals("Forms"))
            //    LoginName = Membership.GetUser().ProviderName + ":" + Membership.GetUser().UserName;
            //else
            //    LoginName = HttpContext.Current.User.Identity.Name;

            if (Request.QueryString["accountname"] != null)
                LoginName = Request.QueryString["accountname"].ToString();
            else
                LoginName = HttpContext.Current.User.Identity.Name;

            string[] Result;
            char[] dim = { '\\' };
            Result = LoginName.Split(dim);

            return Result[1];
        }
        #endregion        

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            GetInfo();

            if (!IsPostBack)
            {
                Default();
            }           
        }

        #region Method

        #region private void GetInfo()
        /// <summary>
        /// 
        /// </summary>
        private void GetInfo()
        {
            //관리자의 경우 버튼을 표시
            this.btnSave.Visible = true;

            strWebUrl = HttpUtility.UrlDecode(strConvertToString(Request.QueryString["pweburl"]));
            strListId = HttpUtility.UrlDecode(strConvertToString(Request.QueryString["plistid"]));
            strItemId = HttpUtility.UrlDecode(strConvertToString(Request.QueryString["itemid"]));
            strItemUrl = HttpUtility.UrlDecode(strConvertToString(Request.QueryString["itemurl"]));
            strPItemUrl = HttpUtility.UrlDecode(strConvertToString(Request.QueryString["pitemurl"]));
            strCrrDepth = HttpUtility.UrlDecode(strConvertToString(Request.QueryString["depth"]));
        }
        #endregion

        #region private void Default()
        /// <summary>
        /// 
        /// </summary>
        private void Default()
        {
            try
            {
                if (!string.IsNullOrEmpty(strWebUrl) && !string.IsNullOrEmpty(strListId) && !string.IsNullOrEmpty(strItemId) && !string.IsNullOrEmpty(strItemUrl) && !string.IsNullOrEmpty(strPItemUrl))
                {
                    GetData();
                    GetPermission();
                }
                else
                {
                    //return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region private void GetData()
        /// <summary>
        /// 폴더 및 아이템의 정보를 가져온다.
        /// </summary>
        private void GetData()
        {
            using (SPSite _site = new SPSite(strWebUrl))
            {
                using (SPWeb _web = _site.OpenWeb())
                {
                    #region Get folder
                    if (_web.DoesUserHavePermissions(SPBasePermissions.BrowseDirectories))
                    {
                        string url = _web.ServerRelativeUrl + "/" + strItemUrl;
                        SPFolder folder = _web.GetFolder(url);

                        try
                        {
                            Guid id = folder.UniqueId;
                            folder = _web.GetFolder(id);
                            url = folder.ServerRelativeUrl;

                            //this.ltData.Text = folder.Name + " / " + url;
                            this.txtName.Text = folder.Name;
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else
                    {
                        // To do
                    }
                    #endregion
                }
            }
        }
        #endregion

        #region private void GetPermission()
        /// <summary>
        /// 폴더 및 아이템의 정보를 가져온다.
        /// </summary>
        private void GetPermission()
        {
            using (SPSite _site = new SPSite(strWebUrl))
            {
                using (SPWeb _web = _site.OpenWeb())
                {
                    #region Get folder
                    if (_web.DoesUserHavePermissions(SPBasePermissions.BrowseDirectories))
                    {
                        string url = _web.ServerRelativeUrl + "/" + strItemUrl;
                        SPFolder folder = _web.GetFolder(url);

                        string strIsDefault = "Default";

                        if (folder.Item.HasUniqueRoleAssignments)
                            strIsDefault = "Friends";
                        else
                            strIsDefault = "Default";

                        try
                        {
                            for (int i = 0; i < this.rblPermission.Items.Count; i++)
                            {
                                if (this.rblPermission.Items[i].Value == strIsDefault)
                                {
                                    this.rblPermission.Items[i].Selected = true;
                                    break;
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else
                    {
                        // To do
                    }
                    #endregion
                }
            }
        }
        #endregion

        #region 폴더 리네임 - SetFolderData()
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strwebUrl"></param>
        /// <param name="strItemUrl"></param>
        private void SetFolderData()
        {
            #region Log Setting
            bool bSave = false;
            SquareActivities aType = new SquareActivities();
            SquareActivityHelper sHelper = new SquareActivityHelper();
            #endregion

            SPUtility.ValidateFormDigest();
            Guid gListId = new Guid(strListId);
            int iItemId = Convert.ToInt32(strItemId);
            string strOldName = string.Empty;
            string strNewName = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(strWebUrl))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;

                        string url = spWeb.ServerRelativeUrl + "/" + strItemUrl;
                        SPFolder folder = spWeb.GetFolder(url);
                        strOldName = folder.Name;

                        try
                        {
                            string strNewUrl = strPItemUrl + "/" + this.txtName.Text;
                            folder.MoveTo(strNewUrl);
                            strNewName = this.txtName.Text;

                            #region Log
                            aType = SquareActivities.SquareDocFolderRename;
                            bSave = sHelper.SaveActivity(this.Page, aType, string.Format(GetTextResource("SquareRes", "SquareDocFolderRename"), strOldName, strNewName));
                            #endregion
                        }
                        catch (Exception ex)
                        {
                        }

                        spWeb.Update();
                        spWeb.AllowUnsafeUpdates = false;
                    }
                }                
            });
        }
        #endregion

        #region 폴더 생성 - private void folderCreate(string strFolderName)
        /// <summary>
        /// UI단에서 이루어지는 문서 이동, 폴더 생성 등의 설정을 적용한다. - 버튼 클릭 시 실행된다.
        /// </summary>
        /// <param name="strEventType">이벤트타입 1:아이템이동, 2:아이템복사, 3:폴더생성</param>
        /// <param name="strFromSiteUrl">문서를 가져올 사이트 주소</param>
        /// <param name="strFromWebName">문서를 가져올 웹 이름</param>
        /// <param name="strFromListUrl">문서를 가져올 리스트 주소</param>
        /// <param name="strFromDocID">가져올 문서 아이디</param>
        /// <param name="strToSite">문서를 옮길 사이트 주소</param>
        /// <param name="strToWebName">문서를 옮길 웹 이름</param>
        /// <param name="strToList">문서를 옮길 리스트 주소</param>
        /// <param name="strToFolder">문서를 옮길 폴더명</param>
        private void folderCreate(string strFolderName)
        {
            #region Log Setting
            bool bSave = false;
            SquareActivities aType = new SquareActivities();
            SquareActivityHelper sHelper = new SquareActivityHelper();
            #endregion

            try
            {
                SPUtility.ValidateFormDigest();

                using (SPSite _site = new SPSite(strWebUrl))
                {
                    using (SPWeb _web = _site.OpenWeb())
                    {
                        SPList _list = _web.GetList(strListId);
                        SPFolder CrrFolder = _web.GetFolder(strPItemUrl);

                        if (CrrFolder != null)
                        {
                            bool IsExsit = false;

                            #region 생성하려는 폴더와 이름이 같은 폴더가 존재한다면
                            if (CrrFolder.SubFolders.Count > 0)
                            {
                                foreach (SPFolder _folder in CrrFolder.SubFolders)
                                {
                                    if (_folder.Name == strFolderName)
                                    {
                                        IsExsit = true;
                                        break;
                                    }
                                }
                            }
                            #endregion

                            #region 폴더 생성
                            if (IsExsit)
                            {
                                Guid uniqueID = Guid.NewGuid();
                                byte[] bArr = uniqueID.ToByteArray();
                                int autonum = BitConverter.ToInt32(bArr, 0);

                                CrrFolder.SubFolders.Add(CrrFolder.ServerRelativeUrl + "/" + strFolderName + "_" + autonum.ToString());
                            }
                            else
                            {
                                CrrFolder.SubFolders.Add(CrrFolder.ServerRelativeUrl + "/" + strFolderName);
                            }
                            #endregion

                            #region Log
                            aType = SquareActivities.SquareDocFolderCreate;
                            bSave = sHelper.SaveActivity(this.Page, aType, string.Format(GetTextResource("SquareRes", "SquareDocFolderCreate"), strFolderName));
                            #endregion
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 폴더 권한 변경 - SetPermission()
        /// <summary>
        /// 폴더 권한 변경
        /// </summary>
        /// <param name="strwebUrl"></param>
        /// <param name="strItemUrl"></param>
        private void SetPermission(string strPermissionType)
        {
            if (string.IsNullOrEmpty(strPermissionType)) return;

            #region Log
            bool bSave = false;
            SquareActivities aType = new SquareActivities();
            SquareActivityHelper sHelper = new SquareActivityHelper();
            #endregion            

            #region Setting
            SPUtility.ValidateFormDigest();
            Guid gListId = new Guid(strListId);
            int iItemId = Convert.ToInt32(strItemId);
            SPPrincipal spPrincipal = null;
            SPRoleAssignment spRoleAssignment = null;
            SPUser CrrUser = SPContext.Current.Web.AllUsers[HttpContext.Current.User.Identity.Name.ToString()];                                         
            #endregion

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(strWebUrl))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;

                        #region setting
                        string url = spWeb.ServerRelativeUrl + "/" + strItemUrl;
                        SPFolder folder = spWeb.GetFolder(url);
                        SPListItem _item = folder.Item;
                        // 사용 권한 수준 정의 (관리자, 참가 권한) 
                        SPRoleDefinition spAdminRoleDef = _item.Web.RoleDefinitions.GetByType(SPRoleType.Administrator);
                        SPRoleDefinition spReaderRoleDef = _item.Web.RoleDefinitions.GetByType(SPRoleType.Reader);
                        #endregion

                        try
                        {
                            #region 권한 셋팅
                            switch (strPermissionType)
                            {
                                case "Inherit":
                                    _item.ResetRoleInheritance();
                                    break;
                                case "private":
                                    if (!_item.HasUniqueRoleAssignments) _item.BreakRoleInheritance(false);
                                    spPrincipal = CrrUser as SPPrincipal;
                                    SPRoleAssignmentCollection current_roles = _item.RoleAssignments;
                                    for (int i = 0; i < current_roles.Count; i++)
                                    {
                                        if (current_roles[i].Member.LoginName.ToLower() != spPrincipal.LoginName.ToLower())
                                            current_roles.Remove(i);                                  
                                    }
                                    spRoleAssignment = new SPRoleAssignment(spPrincipal);
                                    spRoleAssignment.RoleDefinitionBindings.Add(spAdminRoleDef);
                                    _item.RoleAssignments.Add(spRoleAssignment);
                                    break;
                                case "friends":
                                    string strCrrAccount = string.Empty;                                    
                                    strCrrAccount = GetCurrentUserLoginName();
                                    if (!string.IsNullOrEmpty(strCrrAccount))
                                    {
                                        SPGroup grFriends = null;
                                        grFriends = spWeb.SiteGroups["FrGroup_" + strCrrAccount];

                                        if (grFriends != null)
                                        {
                                            spPrincipal = grFriends as SPPrincipal;
                                            spRoleAssignment = new SPRoleAssignment(spPrincipal);
                                            spRoleAssignment.RoleDefinitionBindings.Add(spReaderRoleDef);
                                            _item.RoleAssignments.Add(spRoleAssignment);
                                        }
                                    }
                                    break;
                                case "public":
                                    SPUser spAllUser = _item.Web.AllUsers["NT AUTHORITY\\Authenticated Users"];
                                    spPrincipal = spAllUser as SPPrincipal;
                                    spRoleAssignment = new SPRoleAssignment(spPrincipal);
                                    spRoleAssignment.RoleDefinitionBindings.Add(spReaderRoleDef);
                                    _item.RoleAssignments.Add(spRoleAssignment);
                                    break;
                            }
                            #endregion

                            #region Log
                            aType = SquareActivities.SquareDocFolderPermission;
                            bSave = sHelper.SaveActivity(this.Page, aType, string.Format(GetTextResource("SquareRes", "SquareDocFolderPermission"), folder.Name, strPermissionType)); //"xxx님이 xxx 폴더의 권한을 xxx로 변경하였습니다.");
                            #endregion
                        }
                        catch (Exception ex) { _item.ResetRoleInheritance(); }

                        _item.SystemUpdate(false);
                        spWeb.Update();
                        spWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }
        #endregion

        #endregion

        #region Event

        #region public void btnSave_Click(object sender, EventArgs e)
        /// <summary>
        /// 적용 버튼 이벤트
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void btnSave_Click(object sender, EventArgs e)
        {   
            //폴더 생성 및 이름변경
            if (!string.IsNullOrEmpty(this.txtName.Text))
            {
                if (Request.QueryString["itemid"] != null)
                    SetFolderData();
                else
                    folderCreate(this.txtName.Text);               
            }

            //권한 설정
            string strSelected = string.Empty;
            for (int i = 0; i < this.rblPermission.Items.Count; i++)
            {
                if (this.rblPermission.Items[i].Selected == true)
                {
                    strSelected = this.rblPermission.Items[i].Value;
                    break;
                }
            }
            SetPermission(strSelected);

            //commitPopup
            string strScript = "try{window.frameElement.commitPopup();}catch(e){}";
            Page.ClientScript.RegisterClientScriptBlock(GetType(), string.Empty, strScript, true);
        }
        #endregion

        #endregion
    }
}
































